package com.hzzy.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hzzy.bean.BaseInfo;
import com.hzzy.bean.HzClassCheckins;
import com.hzzy.bean.HzClassCourse;
import com.hzzy.bean.HzStudent;
import com.hzzy.enums.UserSessionKeyEnum;
import com.hzzy.service.CheckDataService;
import com.hzzy.service.HzClassCheckinsService;
import com.hzzy.service.HzClassCourseService;
import com.hzzy.service.HzClassDaycourseService;
import com.hzzy.service.HzSemesterService;
import com.hzzy.service.HzStudentService;
import com.hzzy.service.HzSystemService;
import com.hzzy.service.HzTeacherService;
import com.hzzy.utils.DateUtil;

/**
 * 上课点到
 * @author 何剑波
 * 2016年5月11日
 */
@Controller
@RequestMapping("/check")
public class CheckController {
	private static Logger LOGGER = Logger.getLogger(CheckController.class);
	
	@Resource
	private HzStudentService hzStudentService;
	
	@Resource
	private HzSystemService hzSystemService;
	
	@Resource
	private HzClassCourseService hzClassCourseService;
	
	@Resource
	private HzClassCheckinsService hzClassCheckinsService;
	
	@Resource
	private HzClassDaycourseService hzClassDaycourseService;
	
	@Resource
	private CheckDataService checkDataService;
	
	@Resource
	private HzTeacherService hzTeacherServcie;
	
	@Resource
	private HzSemesterService hzSemesterService;
	
	/**
	 * 初始化"点到班级信息"
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "queryClassMenber", method=RequestMethod.POST)
	public String queryClassMember(Model model, HttpServletRequest request) {
		//TODO 获取操作人信息 ，应该从session中获取登陆者信息
		//TODO 现在直接从数据库中获取
		BaseInfo baseInfo = (BaseInfo) request.getSession().getAttribute(UserSessionKeyEnum.BASE_USER_INFO.getValue());
		HzStudent hzStudent = baseInfo.getStudent();
		if (hzStudent != null) {
			// 判断用户职位是否有权限
//			if (hzStudent.getHzClasses() != null && hzStudent.getCadreId() == hzStudent.getHzClasses().getClasscheckCadreid()) {
				boolean isAllow = hzSystemService.getSubmitCheckins(new Date());
				if (!isAllow) {
					model.addAttribute("message", "现在还不能点到哟！");
					return "rightContent.noFindSection";
				}
				//查询当前时间所在节次
				int classTimes = hzSystemService.getCurrentClassTimes();
				if (classTimes == 0) {
					//TODO 表示没有该时间段内 没有课次 
					// 判断当前时间是否在今天课程开始之前 和 结束之间
					String judgeStr = hzSystemService.judgeCurrentTime(new Date());
					if (judgeStr != null) {
						model.addAttribute("message", judgeStr);
					}
					return "rightContent.noFindSection";
				}
				model.addAttribute("classTimes", classTimes);
				// 获取当前课程
				HzClassCourse course = hzClassCourseService.getCurrentCourse(hzStudent.getClassid(), classTimes);
				
				model.addAttribute("classCourse", course);
				//查询所在班级成员
				List<HzStudent> hzStudentList = hzStudentService.findByClassId(hzStudent.getClassid());
				if (course != null ) {
					// 给已点到过的学生附上状态
					hzStudentService.addCheckinsState(hzStudentList, course);
				} else {
					model.addAttribute("semester", hzSemesterService.getHzSemesterByClassId(hzStudent.getClassid()));
				}
				model.addAttribute("studentList", hzStudentList);
//			} else {
//				//没有权限
//				model.addAttribute("message", "没有权限哟！");
//				return "rightContent.noFindSection";
//			}
			
			// 获取当前班级的所有代课老师信息
			model.addAttribute("teacherList", hzTeacherServcie.getHzTeacherByCurrentClassId(hzStudent.getClassid()));
			// 获取可以调课的课程名字
			model.addAttribute("courseList", hzClassCourseService.getChangeCourseData(hzStudent.getClassid()));
			// 允许修改点到的时间的范围
			model.addAttribute("editTime", hzSystemService.getIsEditCheckinsTime());
		}
		return "rightContent.normalReport";
	}
	
	/**
	 * 跳转到修改页
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="queryEditCourse", method=RequestMethod.POST)
	public String queryEditCourse(Model model, HttpServletRequest request) {
		String checkinsId = request.getParameter("checkinsId");
		if (StringUtils.isEmpty(checkinsId)) {
			model.addAttribute("message", "未找到相关数据!");
			return "rightContent.editReportList";
		}
		BaseInfo baseInfo = (BaseInfo) request.getSession().getAttribute(UserSessionKeyEnum.BASE_USER_INFO.getValue());
		HzStudent hzStudent = baseInfo.getStudent();
		if (hzStudent != null) {
			// 判断用户职位是否有权限
//			if (hzStudent.getHzClasses() != null && hzStudent.getCadreId() == hzStudent.getHzClasses().getClasscheckCadreid()) {
				
				// 获取当前课程
				HzClassCourse course = hzClassCourseService.getCourseByClassIdAndCheckinsId(hzStudent.getClassid(), Integer.parseInt(checkinsId));
				model.addAttribute("classCourse", course);
				//查询所在班级成员
				List<HzStudent> hzStudentList = hzStudentService.findByClassId(hzStudent.getClassid());
				if (course != null ) {
					// 给已点到过的学生附上状态
					hzStudentService.addCheckinsState(hzStudentList, course);
				}
				model.addAttribute("studentList", hzStudentList);
//			} else {
//				//没有权限
//				model.addAttribute("message", "没有权限哟！");
//				return "rightContent.noFindSection";
//			}
			
			// 获取当前班级的所有代课老师信息
//			model.addAttribute("teacherList", hzTeacherServcie.getHzTeacherByCurrentClassId(hzStudent.getClassid()));
			// 获取可以调课的课程名字
//			model.addAttribute("courseList", hzClassCourseService.getChangeCourseData(hzStudent.getClassid()));
			// 允许修改点到的时间的范围
			model.addAttribute("editTime", hzSystemService.getIsEditCheckinsTime());
		}
		return "rightContent.editReportDefault";
	}
	
	/**
	 * 查询当前点到记录
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="queryCheckRecord", method=RequestMethod.POST)
	public String queryCheckRecordList(Model model, HttpServletRequest request) {
		//TODO 获取操作人信息 ，应该从session中获取登陆者信息
		//TODO 现在直接从数据库中获取
		
		// 判断 当前时间是否超时了
		String isAllow = hzSystemService.getIsEditCheckinsTime();
		if (DateUtil.dateContrast(DateUtil.dateFormat("HH:ss", new Date()), isAllow, "HH:ss") == 1) {
			model.addAttribute("message", "已经过了" +isAllow + ", 不能修改咯!");
			return "rightContent.noFindSection";
		}
		BaseInfo baseInfo = (BaseInfo) request.getSession().getAttribute(UserSessionKeyEnum.BASE_USER_INFO.getValue());
		HzStudent hzStudent = baseInfo.getStudent();
		
		if (hzStudent != null) {
			// 判断用户职位是否有权限
//			if (hzStudent.getHzClasses() != null && hzStudent.getCadreId() == hzStudent.getHzClasses().getClasscheckCadreid()) {
				List<HzClassCheckins> list = hzClassCheckinsService.getCheckinsInfoListByClassId(hzStudent.getClassid());
				if (list == null || list.size() == 0) {
					model.addAttribute("errorMsg", "未找到相关数据!");
				}
				model.addAttribute("checkinsList", list);
				// 允许修改点到的时间的范围
				model.addAttribute("editTime", hzSystemService.getIsEditCheckinsTime());
//			}else {
//				//没有权限
//				model.addAttribute("message", "没有权限哟！");
//				return "rightContent.noFindSection";
//			}
		}
		return "rightContent.editReportList";
	}
	
	/**
	 * 修改或新增点到状态
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="changeCheckstudentAttend", method=RequestMethod.POST)
	public Map insertCheckRecord(Model model, HttpServletRequest request){
		// 每次访问的都需要判断当前用户权限
		String courseId = request.getParameter("courseId");// 课程名Id
		String section = request.getParameter("section");// 节次
		String teacherId = request.getParameter("teacherId");// 老师Id
		String students = request.getParameter("students");//学生点到信息

		String dayCourseId = request.getParameter("dayCourseId");// 周表Id
		
		String changeCurseId = request.getParameter("changeCuseid"); // 调过课的id
		String changeSection = request.getParameter("changeSection"); // 调过的节次
		String changeTeacherId = request.getParameter("changeTeacherId"); // 调过课的老师
		
		if (StringUtils.isNotEmpty(changeCurseId)) {
			courseId = changeCurseId;
		} 
		if (StringUtils.isNotEmpty(changeSection)) {
			section = changeSection;
		} 
		if (StringUtils.isNotEmpty(changeTeacherId)) {
			teacherId = changeTeacherId;
		} 
		
		
		// 返回页面的结果集
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("state", false);
		resultMap.put("showDiv", ".alert-danger");

		// 校验
		try {
			boolean b = checkDataService.checkCurseId(Integer.parseInt(courseId));
			if (!b) {
				resultMap.put("resultMsg", "该课程不存在，请重新选择！");
				return resultMap;
			}
			b = checkDataService.checkTeacherId(teacherId);
			if (!b) {
				resultMap.put("resultMsg", "该老师不存在，请重新选择！");
				return resultMap;
			}
		} catch (Exception ex) {
			LOGGER.error(ex);
			resultMap.put("resultMsg", "数据不合法，请重新选择！");
			return resultMap;
		}
		
		BaseInfo baseInfo = (BaseInfo) request.getSession().getAttribute(UserSessionKeyEnum.BASE_USER_INFO.getValue());
		HzStudent hzStudent = baseInfo.getStudent();
		String checkStudentSno = hzStudent.getSno();
		String classId = "1221";
		if (StringUtils.isNotEmpty(courseId) && StringUtils.isNotEmpty(section) && 
				StringUtils.isNotEmpty(teacherId)) {
			int insertCount = hzClassCheckinsService.recordCheckin(classId, checkStudentSno, courseId, section, teacherId, students);
			if (insertCount == -1) {
				resultMap.put("resultMsg", "不能重复点到！");
				resultMap.put("state", true);
			} else {
				if (StringUtils.isNotEmpty(dayCourseId)) {
					// 更新周表签到记录
					hzClassDaycourseService.updateIsCheckins(dayCourseId);
					// 更新调课的状态
					if (!courseId.equals(request.getParameter("courseId"))) {
						//如果不一样，那么说明调整过课
						hzClassDaycourseService.updateIsChangeCourse(dayCourseId);
					}
				} 
				if (StringUtils.isNotEmpty(students) && students.split("-").length == 3){
					resultMap.put("isNotEnabled", true);
				}
				resultMap.put("resultMsg", "提交成功!`(*∩_∩*)′");
				resultMap.put("state", true);
				resultMap.put("showDiv", ".alert-success");
			}
		}
		return resultMap;
	}
}
